package cn.nubia.admin.common.shiro.filter;

import cn.nubia.admin.common.shiro.handler.ExtCodeConverter;
import cn.nubia.admin.common.shiro.handler.PermissionExtAnnotationHandler;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * url match 方式验证过滤器
 */
public class PermissionsExtAuthorizationFilter extends AuthorizationFilter {
    private final static Logger logger = LoggerFactory.getLogger(PermissionExtAnnotationHandler.class);




    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        Subject subject = getSubject(request, response);
        String[] perms = (String[]) mappedValue;


        ExtCodeConverter codeConverter = new ExtCodeConverter();
        for (int i = 0 ;i< perms.length ;i++) {
            perms[i] = codeConverter.convertContextId(perms[i]);
        }

        if (logger.isInfoEnabled()) {
            logger.info("in filter ,perms is:"+ Arrays.toString(perms));
        }

        boolean isPermitted = true;
        if (perms.length > 0) {
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }

        return isPermitted;
    }
}
